<?php
/**
*
* 功能描述（收藏控制器）
*
* @author suoya <jlusuoya@gmail.com>
* @version 1
*/

class CtrlFavorite extends CtrlBase
{
	public $paramCheck = array(
		"add" => array(
			'good_id' => array("GET", "must", "intval", "positive"),
		),
		"remove" => array(
			'good_id' => array("GET", "must", "intval", "positive"),
		),
		"showlist" => array(
			"page" => array("GET", "1", "intval", "positive"),
		),
	);

	public $perms = array(
		"add" => array(1, 255, "index.php?action=user.tologin"),
		"showlist" => array(1, 255, "index.php?action=user.tologin"),
		"remove" => array(1, 255, "index.php?action=user.tologin"),
	);

	function Add()
	{
		$id = $this->params['good_id'];
		$obj = $this->GetModel("Food");
		$data = $obj->GetGoods($id);
		if(!$data)
		{
			$this->assign("msg", "商品已不存在");
			return RT_MSG;
		}
		//检查
		$fobj = $this->GetModel("Favorite");
		$ver = $fobj->GetItem($this->user->userid, $id);
		if($ver) //已收藏
		{
			if($ver['version'] == $data['version'])
			{
				$this->assign("msg", "已经在此时间收藏过该商品: " . $data['updatetime']);
				return RT_MSG;
			}
			//update
			$fild = array("name" => $data['name'], "version" => $data['version']);
			$ret = $fobj->SaveItem($fild, $this->user->userid, $id);
			$msg = "收藏过旧版本，保存更新";
		}
		else
		{
			$fild = array(
				"name" => $data['name'],
				"version" => $data['version'],
				"userid" => $this->user->userid,
				"goodid" => $id,
			);
			//insert
			$ret = $fobj->NewItem($fild);
			if($ret <= 0)
				$msg = "添加收藏出错";
			else
				$msg = "添加收藏成功";
		}
		$this->assign("msg", $msg);
		return RT_MSG;
	}

	function Remove()
	{
		$fobj = $this->GetModel("Favorite");
		$ret = $fobj->RemoveItem($this->user->userid, $this->params['good_id']);
		if($ret == 0)
			$msg = "收藏不存在";
		else 
			$msg = "移除收藏成功";
		$this->assign("msg", $msg);
		return RT_MSG;
	}

	function ShowList()
	{
		$fobj = $this->GetModel("Favorite");
		$data = $fobj->GetList($this->user->userid, $this->params['page']);
		$this->assign("goodsList", $data['data']);
		$this->assign("totalCnt", $data['cnt']);
		$this->assign("pageCnt", $data['pageCnt']);
		$this->assign("curPage", $this->params['page']);
		return RT_TPL;
	}
}

